package com.ecreditpal.audio.platform.baidu;

import com.baidu.aip.speech.AipSpeech;
import com.ecreditpal.audio.AsrCallback;
import com.ecreditpal.audio.AsrRunner;
import com.ecreditpal.audio.model.AudioSession;
import com.ecreditpal.audio.platform.Config;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Created by lishunyi on 2018/6/15
 */
@Slf4j
public class BaiduAsr extends AsrRunner {
    private AipSpeech client;
    private Config config;

    @Override
    public void init(Config config) {
        log.info("[Init]初始化AipSpeech");
        this.client = new AipSpeech(config.getAppId(), config.getAppKey(),config.getAppSecret());
        this.client.setConnectionTimeoutInMillis(2000);
        this.client.setSocketTimeoutInMillis(600000);
        this.config = config;
        log.info("[Init]Success!");
    }


    @Override
    public void process(byte[] data,AsrCallback callback) {
        try {

            JSONObject res = this.client.asr(data, "wav", config.getByteRate(), null);
            JSONArray array = res.getJSONArray("result");
            if (array.length() > 0) {
                String response = array.get(0).toString();
                callback.sendMessage(response);
            }
        } catch (Exception e) {
            log.error("can not transform audio to txt",e);
        }
    }
}
